package module

import (
	"crypto/md5"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net"
	"net/http"
	"strconv"
	"strings"
	"time"
)

type Msg struct {
	Body interface{}
	Code int
}

func NewMap() map[string]string {
	return make(map[string]string)
}
func NewToken() string {
	ct := time.Now().Unix()
	h := md5.New()
	io.WriteString(h, strconv.FormatInt(ct, 10))
	token := fmt.Sprintf("%x", h.Sum(nil))
	return token
}
func requestLog(w http.ResponseWriter, r *http.Request) {
	code := w.Header().Get("ErrorHeaderCode")
	if code == "" {
		code = "OK"
	}
	fmt.Println("[", r.Method, "]", code, r.URL.String())
}
func ReturnErr(w http.ResponseWriter, body string, code int) {
	b, e := json.Marshal(Msg{Body: body, Code: code})
	if e != nil {
		w.Write([]byte(`{"Body":"` + e.Error() + `","Code":-101}`))
		return
	}
	w.Write(b)
}
func ReturnInfo(w http.ResponseWriter, body string) {
	b, e := json.Marshal(Msg{Body: body, Code: 200})
	if e != nil {
		w.Write([]byte(`{"Body":"` + e.Error() + `","Code":-101}`))
		return
	}
	w.Write(b)
}
func DoPostForm(url string, m map[string]string) (string, string, error) {
	var r http.Request
	r.ParseForm()
	for k, v := range m {
		r.Form.Add(k, v)
	}
	bdstr := strings.TrimSpace(r.Form.Encode())
	request, e := http.NewRequest("POST", url, strings.NewReader(bdstr))
	if e != nil {
		return "", "", e
	}
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	request.Header.Set("Connection", "Keep-Alive")
	rp, e := http.DefaultClient.Do(request)
	if e != nil {
		return "", "", e
	}
	defer rp.Body.Close()
	data, e := ioutil.ReadAll(rp.Body)
	if e != nil {
		return "", "", e
	}
	return string(data), rp.Header.Get("ErrorHeaderCode"), nil
}

func GetIP() string {
	ifaces, err := net.Interfaces()
	if err != nil {
		fmt.Println(err)
		return ""
	}
	var strs []string
	for _, i := range ifaces {
		addrs, err := i.Addrs()
		if err != nil {
			fmt.Println(err)
			continue
		}
		for _, addr := range addrs {
			switch v := addr.(type) {
			case *net.IPNet:
				ip := v.IP
				strs = append(strs, ip.String())
			case *net.IPAddr:
				// ip := v.IP
				// strs = append(strs, ip.String())
			}
		}
	}
	for _, v := range strs {
		if len(v) > 8 && v[:8] == "192.168." {
			return v
		}
	}
	for _, v := range strs {
		if len(v) > 3 && v[:3] == "10." {
			return v
		}
	}
	for _, v := range strs {
		if len(v) > 4 && v[:4] == "172." {
			return v
		}
	}
	for _, v := range strs {
		if v != "127.0.0.1" && v != "::1" && len(v) < 16 {
			return v
		}
	}
	return "127.0.0.1"
}
